-- Gamemode
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include( 'shared.lua' )
include( 'player.lua' )

function GM:Initialize( )
	self.Rides = {}
end

function GM:BuyTicket(ply,ridename,cost)
	if ply.Ticket != ridename then
		if (ply:GetTokens() >= cost) then 
			ply.Ticket = ridename
			ply:SubTokens(cost)
			ply:ChatPrint( "FunFair: You have purchased a ticket for ".. ridename ..".")
		else
			ply:ChatPrint( "FunFair: You do not have enough tokens for ".. ridename ..".")
		end
	else
	ply:ChatPrint( "FunFair: You already have a ticket for ".. ridename ..".")
	end
end

function GM:PlayerInitialSpawn( pl )
	pl:LoadPlayerData()
end

function GM:PlayerDisconnected( ply )
	ply:SavePlayerData()
end

hook.Add( "ShutDown", "ShutMeDownSave", function()
	for k, v in pairs( player.GetAll() ) do
		v:SavePlayerData()
	end
end )

function SendToAll(text)
	for k,v in pairs(player.GetAll()) do
		v:ChatPrint("FunFair: " ..text)
	end
end

timer.Simple( 1 * 60, function() 
	for k,v in pairs( player.GetAll() ) do 
		v:SavePlayerData() 
	end
	SendToAll("Autosave Complete.")
end )

function GM:InitPostEntity( )
	self:IncludeRides()
	for _,RIDE in pairs(GAMEMODE.Rides) do
		RIDE:Initialize()
		RIDE:GetScreen():SetNetworkedString( "label", RIDE.NAME)
		RIDE:GetScreen():SetNetworkedInt( "cost", RIDE.COST)
	end
end

function GM:CanPlayerEnterVehicle( player, vehicle, role )
	if vehicle.FakeParent.Locked then
		return false
	end
	return true 
end

function GM:CanExitVehicle ( vehicle, ply )
	if vehicle.FakeParent.Locked then
		return false
	end
	return true 
end

function GM:RideValid(rideid)
	if GAMEMODE.Rides[rideid] != nil then
		return true
	end
	
	print(tostring(rideid).." is not a valid ride.")
	PrintTable(GAMEMODE.Rides)
	return false
end

local function CCStartRide(ply,cmd,args)
	local rideid = string.Implode(" ",args)
	if GAMEMODE:RideValid(rideid) then
		GAMEMODE.Rides[rideid]:Start()
	end
end
concommand.Add( "ff_startride", CCStartRide )

local function CCStopRide(ply,cmd,args)
	local rideid = args[1]
	if GAMEMODE:RideValid(rideid) then
		GAMEMODE.Rides[rideid]:Stop()
	end
end
concommand.Add( "ff_stopride", CCStopRide )

function GM:AddRide(RIDE)
	GAMEMODE.Rides[RIDE.NAME] = RIDE
	hook.Add("Think","ffRideThink"..RIDE.NAME,function() RIDE:Think() end)
end

function GM:IncludeRides()
	local Folder = string.Replace( self.Folder, "gamemodes/", "" ); -- returns "funfair"
	local subfolder = "/gamemode/rides/"
	for c,d in pairs(file.FindInLua(Folder..subfolder.."*.lua")) do
		include( Folder..subfolder..d )
		--AddCSLuaFile( Folder..subfolder..d )
	end
end

function GM:PlayerLoadout( pl )
	pl:Give( "weapon_physcannon" )
end

function GM:GravGunPickupAllowed( ply, ent )
	if (ent:IsValid() && (ent:GetClass() == "ffseat")) then
		return false
	end
end

function GM:GravGunPunt( ply, ent ) 
	if (ent:IsValid() && (ent:GetClass() == "ffseat" or ent:GetClass() == "ffscreen")) then
		return false
	end
end